<template>
  <div class="file-upload" :style="{ display: option.verticalLayout ? 'block' : 'flex' }">
    <el-upload
      v-if="!option.disabled"
      class="upload-btn"
      :action="uploadUrl"
      :on-success="uploadSuccess"
      :before-upload="beforeUpload"
      :show-file-list="false"
      :file-list="fileList"
    >
      <el-button
        v-if="!provideDisabled || !option.disabled"
        icon="el-icon-upload2"
        size="medium"
        :disabled="option.disabled"
        type="primary"
        plain
      >上传
      </el-button>
    </el-upload>
    <zk-file-list
      v-model="fileList"
      :vertical-layout="option.verticalLayout"
    />
  </div>
</template>
<script>
  import { ossUri } from '@/common/zk-constants'
  import ZkFileList from '@/components/zk-review-file-list'
  const {uploadUrl, downloadUrl } = ossUri
  // todo 因后端接口不规范  本组件无法通用 需要定规范后改造

  // todo
  const respTransfer = (file = {}, payload = {}) => {
    const { bucketName, fileId, name, fileName } = payload
    return Object.assign(file, {
      ...payload,
      fileId,
      bucketName,
      name: name || fileName,
      fileName: name || fileName,
      fileUrl: `${downloadUrl}${fileId}`
    })
  }
  export default {
    name: 'Upload',
    components: { ZkFileList },
    inject: {
      provideDisabled: {
        type: Boolean,
        default: false,
      }
    },
    model: {
      prop: 'propValue',
      event: 'onChange',
    },
    props: {
      propValue: {
        type: Array,
        default: () => [],
      },
      option: {
        type: Object,
        default: () => ({}),
      },
      uploadQuery: {
        type: Object,
        default: () => ({}),
      }
    },
    data() {
      const fileList = (this.propValue || []).map(e => respTransfer({}, e))
      return { fileList, uploadUrl }
    },
    watch: {
      fileList(v) {
        this.$emit('onChange', v)
      },
      propValue(newValue = []) {
        newValue.forEach(e => respTransfer(e, e))
        this.fileList = newValue
      }
    },
    methods: {
      uploadSuccess(res, file, fileList) {
        const { code, payload } = res
        if (code === 0) {
          respTransfer(file, payload)
          file.fieldName = this.option.key
          file.fieldId = this.option.key
          this.$emit('onChange', fileList)
        }
      },
      beforeUpload(file) {
        const { acceptTypes = [], maxSize = 500 } = this.option
        const checkType = acceptTypes.includes(file.type) || !acceptTypes.length
        const checkSize = file.size / 1024 / 1024 < maxSize

        if (!checkType) {
          this.$message.error(`上传头像图片只能是 ${acceptTypes.join('/')} 格式!`)
        }
        if (!checkSize) {
          this.$message.error(`上传头像图片大小不能超过 ${maxSize}MB!`)
        }
        return checkType && checkSize
      }
    },
  }
</script>
<style scoped lang="scss">
  .file-upload {
    display: flex;
    flex-wrap: nowrap;
  }
</style>
